#include "Requester.h"
namespace request_manager
{

	CURL* Requester::curl = NULL;
	Response Requester::response;
	char  Requester::errorBuffer[CURL_ERROR_SIZE];

	void Requester::init()
	{
		curl_global_init(CURL_GLOBAL_ALL);
	}

	size_t Requester::write_callback(char* ptr, size_t size, size_t nmemb, void *userdata)
	{
		Requester::response.data.append(ptr, size * nmemb);

		return size *nmemb;
	}

	Response Requester::_doGET(Request* request)
	{
		Requester::curl = curl_easy_init();

		//Proxy, SSL, Follow Location settings
		curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
		curl_easy_setopt(curl, CURLOPT_PROXY, "");
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response.data);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

		curl_easy_setopt(curl, CURLOPT_POST, false);
		curl_easy_setopt(curl, CURLOPT_HTTPGET, true);
		
		curl_easy_setopt(curl, CURLOPT_URL, request->url.c_str());

		response = _do();

		curl_easy_cleanup(curl);
		
		return response;
	}

	Response Requester::_doPOST(Request* request)
	{
		Requester::curl = curl_easy_init();

		curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
		curl_easy_setopt(curl, CURLOPT_PROXY, "");
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response.data);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

		curl_easy_setopt(curl,CURLOPT_URL, request->url.c_str());
		curl_easy_setopt(curl, CURLOPT_POST, true);
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request->data.c_str());
		
		response = _do();
		
		curl_easy_cleanup(curl);

		return response;
	}

	Response Requester::_do()
	{
		CURLcode res;

		res = curl_easy_perform(curl);

		if (res != CURLE_OK)
		{
			fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
		}
		else
		{
			curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response.http_code);
		}

		return response;
	}
}